import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Tabs, Spin } from 'antd'
const TabPane = Tabs.TabPane;
import menuRoute from 'routes/menuRoute'
import expenseTypeService from 'containers/setting/expense-type/expense-type.service'
import ExpenseTypeBase from 'containers/setting/expense-type/new-expense-type/expense-type-base'
import ExpenseTypeCustom from 'containers/setting/expense-type/new-expense-type/expense-type-custom/expense-type-custom'
import ExpenseTypeScope from 'containers/setting/expense-type/new-expense-type/expense-type-scope'
import ExpenseTypeStandard from 'containers/setting/expense-type/new-expense-type/expense-type-standard'
import { setExpenseTypeSetOfBooks } from 'actions/setting'

class NewExpenseType extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      tabs: [
        {key: 'base', name: messages('setting.key583'/*基础信息*/)},
        {key: 'custom', name: messages('setting.key584'/*详情设置*/)}
      ],
      loading: false,
      nowTab: 'base',
      expenseType: null,
      index: -2
    }
  }

  //Tabs点击
  onChangeTabs = (key) => {
    const { profile, expenseTypeSetOfBooks } = this.props;
    if(key === 'subsidy'){
      this.context.router.push(menuRoute.getRouteItem(profile['All.NewAllowance.Enable'] ? 'base-subsidy' : 'travel-policy').url + `?setOfBooksId=${expenseTypeSetOfBooks.id}`);
    } else {
      this.setState({nowTab : key})
    }
  };

  getExpenseType = (target, id = this.props.params.expenseTypeId) => {
    this.setState({ loading: true });
    let { tabs } = this.state;
    let { languageList } = this.props;
    let { copy } = this.props.params;
    expenseTypeService.getExpenseTypeDetail(id, copy).then(res => {
        let expenseType = JSON.parse(JSON.stringify(res.data));
        if (expenseType.supplierType === 0 && expenseType.isAbleToCreatedManually && tabs.length === 2) {
          tabs.push({ key: 'scope', name: messages('setting.key585'/*权限设置*/) });
        }
      tabs.filter(tab => tab.key === 'standard').length === 0 && tabs.push({
        key: 'standard',
        name: messages('setting.key1541')/*费用标准设置*/
      });
      expenseType.fields = res.data.fields.sort((a, b) => a.sequence > b.sequence || -1);
      expenseType.apportionEnabledConfig = [];// 分摊组 （申请单，报销单）
      expenseType.erApportionEnabled && expenseType.apportionEnabledConfig.push('erApportionEnabled'); // 申请单
      expenseType.apportionEnabled && expenseType.apportionEnabledConfig.push('apportionEnabled'); // 报销单
      expenseType.fields.map(item => {
        //i18n name值没有初始化时手动初始化
        if(!item.i18n){
          item.i18n = {};
        }
        if(!item.i18n.name){
          item.i18n.name = [];
          languageList.map(language => {
            item.i18n.name.push({
              language: language.code.toLowerCase(),
              value: item.name
            })
          });
        }
      });
      this.setState({ expenseType, loading: false, tabs });
      this.props.dispatch(setExpenseTypeSetOfBooks({
        id: expenseType.setOfBooksId,
        setOfBooksName: expenseType.setOfBooks.setOfBooksName,
        functionalCurrencyCode: expenseType.setOfBooks.functionalCurrencyCode
      }));
      target && this.setState({ nowTab: target })
    })
  };

  componentWillMount(){
    let id = this.props.params.expenseTypeId;
    if(id){
      this.getExpenseType()
    }
  }

  renderTabs() {
    const { copy, expenseTypeId } = this.props.params;
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key} disabled={tab.key !== 'base' && (!expenseTypeId || !!copy)}/>;
      })
    );
  }

  getExpenseTypeComponents = () => {
    const { nowTab, expenseType, index, structureNowWidget } = this.state;
    const { copy } = this.props.params;
    switch (nowTab) {
      case 'base':
        return <ExpenseTypeBase expenseType={expenseType} onSave={this.getExpenseType} copy={!!copy}/>;
      case 'custom':
        return <ExpenseTypeCustom expenseType={expenseType}
                                  onSave={this.getExpenseType}
                                  saveIndex={(index, structureNowWidget) => this.setState({
                                    index,
                                    structureNowWidget
                                  })}
                                  index={index}
                                  structureNowWidget={structureNowWidget}
                                  expenseTypeId={this.props.params.expenseTypeId}
        />;
      case 'scope':
        return <ExpenseTypeScope expenseType={expenseType} onSave={this.getExpenseType}/>;
      case 'standard':
        return <ExpenseTypeStandard expenseType={expenseType} onSave={this.getExpenseType}/>;
    }
  };

  render() {
    const { nowTab, loading } = this.state;
    return (
      <div className="new-expense-type">
        <Tabs onChange={this.onChangeTabs} activeKey={nowTab}>
          {this.renderTabs()}
        </Tabs>
        { loading ? <Spin/> : this.getExpenseTypeComponents() }
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    languageList: state.login.languageList,
    profile: state.login.profile,
    tenantMode: state.main.tenantMode,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks
  }
}
NewExpenseType.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(NewExpenseType)
